package com.zxy.barometer.schedued;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.zxy.barometer.model.City;
import com.zxy.barometer.model.Province;
import com.zxy.barometer.service.CityService;
import com.zxy.barometer.service.ProvinceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author zxy
 */
@Slf4j
@Component
public class WriteDataSchedued {

    private final ProvinceService provinceService;
    private final CityService cityService;

    public WriteDataSchedued(ProvinceService provinceService, CityService cityService) {
        this.provinceService = provinceService;
        this.cityService = cityService;
    }

//    /**
//     * 获取中国天气网省份信息
//     */
//    @PostConstruct
//    public void readProvinceData() {
//        try {
//            String responseMessage = HttpUtil.get("http://www.nmc.cn/f/rest/province", "utf-8");
//            if (StringUtils.isNotBlank(responseMessage)){
//                JSONArray provinceArray = JSONArray.parseArray(responseMessage);
//                log.info("获取省份信息：{}", provinceArray);
//                List<Province> provinceList = provinceArray.toJavaList(Province.class);
//                provinceService.saveBatch(provinceList);
//            }
//        } catch (Exception e) {
//            log.error("同步省份数据出错");
//        }
//    }

//    /**
//     * 循环获取中国天气网城市信息
//     */
//    @PostConstruct
//    public void readCityData() {
//        try {
//            QueryWrapper<Province> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("status", 1);
//            List<Province> provinceList = provinceService.list(queryWrapper);
//            for (Province p : provinceList) {
//                String requestUrl = "http://www.nmc.cn/f/rest/province/"+p.getCode();
//                String responseMessage = HttpUtil.get(requestUrl, "utf-8");
//                log.info(requestUrl);
//                log.info(responseMessage);
//                if (StringUtils.isNotBlank(responseMessage)){
//                    JSONArray cityArray = JSONArray.parseArray(responseMessage);
//                    List<City> cityList = cityArray.toJavaList(City.class);
//                    cityService.saveBatch(cityList);
//                    Thread.sleep(5000);
//                }
//            }
//        } catch (Exception e) {
//            log.error("同步城市数据出错");
//        }
//    }
}
